package cloud.mbase.auth;

import cloud.mbase.util.StringUtil;
import cloud.mbase.util.TokenUtil;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    private UserDetailsService myUserDetailsServiceImpl;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager, UserDetailsService myUserDetailsServiceImpl) {
        super(authenticationManager);
        this.myUserDetailsServiceImpl = myUserDetailsServiceImpl;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader(StringUtil.AUTH);
        if (token != null && token.startsWith(StringUtil.BEARER)) {
            String userName = TokenUtil.getUsernameFromToken(token);
            if (userName != null && userName.length() > 0) {
                UserDetails userDetails = myUserDetailsServiceImpl.loadUserByUsername(userName);
                if(userDetails!=null){
                    if(TokenUtil.validateToken(token,userDetails)){
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                }
            }
        }
        chain.doFilter(request, response);
    }
}
